//
//  EBookProtocol.swift
//  eBooks
//
//  Created by JunMing on 2020/1/16.
//  Copyright © 2020 赵俊明. All rights reserved.
//

import Foundation

protocol EbookBuyProtocol { }
extension EbookBuyProtocol {
    func buyAction(_ view:UIView?) {
        let cancle = AlertItem(title: "取消", icon: nil)
        let restore = AlertItem(title: "恢复购买", icon: nil)
        restore.action = {_ in
            JMBuyHelper().buy_restore()
        }
        let buy = AlertItem(title: Tools.getVip() ? "已经购买过啦😊😊":"请喝咖啡☕️☕️ 18¥", icon: nil)
        buy.action = {_ in
            JMBuyHelper().startBuy({ info in
                let dic = info as! [String:String]
                print(dic)
                if dic["status"] == "0" {
                    
                }else if dic["status"] == "1" {
                    
                }else {
                    
                }
                print(dic["msg"] as Any)
            })
        }
        let feedback = AlertItem(title: "反馈版权问题", icon: nil)
        feedback.action = {_ in
            JMBuyHelper().fadeback_copyright()
        }
        let sheetItem = SheetItem(title: "")
        sheetItem.className = "BookPayView"
        sheetItem.models = [cancle,restore,buy,feedback]
        let manager = SheetManager(superView: view, item: sheetItem)
        sheetItem.sheetType = .buyVip
        manager.update()
    }
}


protocol EbookDownloadProtocol { }
extension EbookDownloadProtocol {
    func downloadRight(superView:UIView) -> Bool {
        let count = EBookDefault.readIntegerByKey(downCount)
        let time = EBookDefault.readDoubleByKey(downTime)
        let sameDay = time.date.isSameDay()
        var status = false
        if sameDay && count < 3 {// 同一天切下载数小于3，允许下载，计数加1
            EBookDefault.setInteger(count+1, downCount)
            status = true
        }else if sameDay && count > 2 {// 同一天切下载数小于3，不允许下载，计数不变
            let left = AlertItem(title: "观看视频", icon: nil)
            left.eventName = kEbooksBuyVipEventName
            let right = AlertItem(title: "取消", icon: nil)
            let item = SheetItem(title: "无法继续下载")
            item.subTitle = "您已经达到限制次数，观看视频广告增加下载次数"
            item.className = "BookInfoAlert"
            item.models = [left,right]
            let manager = SheetManager(superView: superView, item: item)
            item.sheetType = .right
            manager.update()
            status = false
        } else {// 不是同一天，下载数重置，允许下载
            EBookDefault.setInteger(0, downCount)
            status = true
        }
        EBookDefault.setDouble(Date.currentTime, downTime)
        return status
    }
    
    func downloadRun(model:Model,handle: @escaping (_ status:Bool) -> Void) {
        var manager:SheetManager?
        if let view = UIApplication.shared.keyWindow {
            let item = SheetItem(title: "")
            item.sheetType = .animation
            item.className = "HudAnimation"
            manager = SheetManager(superView: view, item: item)
            manager?.update()
        }
        NetHelper.share.downloadWith(urlStr: model.bookurl(), success: { (desc, status) in
            if status {
                model.isdel = false
                model.date = String(format: "%f", arguments: [Date.currentTime])
                SQLHelper.share.updateLocalDB(model, type: .download)
            }else {
                SQLHelper.share.deleteLocalDB(model)
                FileHelper.deleteFile(model.fullname!)
                print("😭😭😭😭😭下载失败")
            }
            handle(status)
            manager?.hide()
        }, progress: { _ in })
    }
}


protocol EbookCellProtocol { }
extension EbookCellProtocol {
    
}

protocol EbookOpenEmailProtocol { }
extension EbookOpenEmailProtocol {
    func openEmail(_ them:String, _ toEmail:String, _ ccEmail:String?, _ content:String) {
        let mailUrl = NSMutableString()
        // 添加收件人
        mailUrl.appendFormat("mailto:%@,", toEmail)
        if let ccmail = ccEmail {
            // 添加抄送
            mailUrl.appendFormat("?cc=%@,", ccmail)
        }
        // 添加主题
        mailUrl.appendFormat("&subject=%@", them)
        // 添加正文
        mailUrl.appendFormat("&body=<b>%@", content)
        let character = NSCharacterSet(charactersIn: "`#%^{}\"[]|\\<> ").inverted
        guard let em = mailUrl.addingPercentEncoding(withAllowedCharacters: character) else { return }
        if let emailUrl = URL(string: em) {
            UIApplication.shared.open(emailUrl, options: [:], completionHandler: nil)
        }
    }
}
